package com.jk.controller;

import com.alibaba.fastjson.JSONObject;
import com.jk.flower.mapper.FlowerRepo;
import com.jk.flower.pojo.Flower;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("flower")
public class FlowerController{

    @Autowired
    FlowerRepo flowerRepo;

    /**页面**/
    @RequestMapping("fid/{flowerid}") //返回花和他的信息到model里面
    public String buyFlower(@PathVariable("flowerid") String flowerId, Model model){
        //TODO 把花的详细信息加入进去
        Flower flower = flowerRepo.findFlowerByFlowerId(flowerId);
        model.addAttribute("flower",flower);
        return "main/pro_show";
    }

    /**数据**/
    @ResponseBody
    @RequestMapping("allflowers")
    public String getAllflowers(HttpServletRequest request, HttpServletResponse response){
        List<Flower> flowerList  = flowerRepo.findAll();
        return "";
    }

    //上传花朵图片
    @RequestMapping("/addflowers")
    @ResponseBody
    public String putFlowerPhoto(HttpServletRequest request, String imageUrl) throws IOException {
        Flower flower = new Flower();
        JSONObject result = new JSONObject();
        MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
        //上传文件
        MultipartFile file = params.getFile("upload");
        String UU = UUID.randomUUID().toString().replace("-","").toLowerCase();
        flower.setFlowerId(UU);
        flower.setId((UUID.randomUUID().toString().replace("-","").toLowerCase()));
        String filePath = writeFile(file,UU);
        String name = params.getParameter("pname");
        Double price = Double.parseDouble(params.getParameter("market_price"));
        String description = String.valueOf(params.getParameter("pdesc"));
        int inventory = Integer.parseInt(params.getParameter("num"));
        int type = Integer.parseInt(params.getParameter("type"));
        result.put("status","20000");
        flower.setFlowerPicture(filePath);
        flower.setFlowerName(name);
        flower.setName(name);
        flower.setAge(3);
        flower.setPrice(price);
        flower.setInventory(inventory);
        flower.setType(type);
        flower.setDescription(description);
        flowerRepo.save(flower);

        return result.toString();
    }

    @ResponseBody
    @RequestMapping("/getIamges/{path}")
    public String fromIdgetImage(ModelAndView mav,@PathVariable("path") String path, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String p = "E:\\project_maven\\flower\\src\\main\\resources\\static\\image\\";
        ServletOutputStream output=response.getOutputStream();
        File file = new File(p + path);
        FileInputStream in = null;

        in = new FileInputStream(file);
        byte[] bytearray = new byte[1024];
        int size;
        while ((size=in.read(bytearray)) != -1){
            output.write(bytearray,0,size);
        }
        in.close();
        output.close();
        return null;
    }

    @ResponseBody
    @RequestMapping("delete/{flowerid}")
    public String deleteFlower(@PathVariable("flowerid")String flowerId){

        JSONObject res = new JSONObject();
        Flower flower = flowerRepo.findFlowerByFlowerId(flowerId);
        if(flower != null){
            flowerRepo.delete(flower);
        }
        res.put("status","20000");

        return res.toString();

    }

    /**
     *
     * @param file
     * @return 文件名
     */
    public String writeFile(MultipartFile file,String UU) throws IOException {
        //获取static目录
        String path = "E:\\project_maven\\flower\\src\\main\\resources\\static\\image\\";
        String pathName = path + UU + ".jpg";
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File(pathName)));
        bufferedOutputStream.write(file.getBytes());
        bufferedOutputStream.flush();
        bufferedOutputStream.close();
        System.out.println(file.getName());
        return pathName;
    }


}
